require 'treenode.rb'
require 'singleton'

class TreeService
    include Singleton
    
    def initialize
        @searchResult = []
        @searchResultIndex = 0
        @displayResult = ''
    end
    
    def cloneNode(originalNode)
        returnNode = TreeNode.new(originalNode.value)
        returnNode.parentNode = originalNode.parentNode
        originalNode.childNodes.each { |childNode| 
            returnNode.addChild(cloneNode(childNode))
        }
        returnNode
    end
    
    def search(startingNode, value, depth=0)
    	return if !startingNode
    	
        if depth == 0
            @searchResult = []
            @searchResultIndex = 0
        end
        
        if startingNode.value != value
            startingNode.childNodes.each { |childNode| search(childNode, value, depth += 1)	}
        else
            @searchResult[@searchResultIndex] = startingNode
            @searchResultIndex += 1
        end
        @searchResult
    end
    
    def printGraph(startingNode, delimiter, depth=0)
        return if !startingNode
        
        if depth == 0 
            @displayResult = ''
        end

        @displayResult.insert(0, startingNode.value)
        @displayResult.insert(0, delimiter)
        
        printGraph(startingNode.parentNode, delimiter, depth += 1)
        
        @displayResult
    end
end